#!/bin/sh

# download and unpack the source files
# if headers are missing on debian, try installing apt-file
# and searching with 'apt-file search <filename>'

if ! test -f 2006_src.tar.gz; then

  wget http://cernlib.web.cern.ch/cernlib/download/2006_source/tar/2006_src.tar.gz

  tar -xzf 2006_src.tar.gz

  # -fPIC is essential for dynamic libs
  sed -e's/-fugly-complex//g
s/\(.define.*CcCmd\s*gcc\)/\1 -fPIC/g
s/\(.define.*FortranCmd\s*\).*/\1 gfortran -fPIC -fno-automatic/g' -i 2006/src/config/linux.cf
  sed -e's/-fugly-complex//g
s/\(.define.*CcCmd\s*gcc\)/\1 -fPIC/g
s/\(.define.*FortranCmd\s*\).*/\1 gfortran -fPIC -fno-automatic/g' -i 2006/src/config/linux-lp64.cf

  # build only packlib and mathlib
  sed -e's/^LIBDIRS=.*/LIBDIRS= packlib mathlib/g' -i 2006/src/Imakefile

fi

# Establish the environment variables for the build procedures
# Depending on the system, other directories may need to be added to the PATH
# e.g. for the build tools and alternative compilers.

CERN_LEVEL=2006

CERN=`pwd`
CERN_ROOT=$CERN/$CERN_LEVEL
CVSCOSRC=$CERN/$CERN_LEVEL/src
PATH=$CERN_ROOT/bin:$PATH

export CERN
export CERN_LEVEL
export CERN_ROOT 
export CVSCOSRC
export PATH

# Create the build directory structure

cd $CERN_ROOT
mkdir -p build bin lib build/log

# Create the top level Makefile with imake

cd $CERN_ROOT/build
$CVSCOSRC/config/imake_boot

# Install kuipc and the scripts (cernlib, paw and gxint) in $CERN_ROOT/bin

gmake bin/kuipc
gmake scripts/Makefile
cd scripts
gmake install.bin

# Install the libraries

cd $CERN_ROOT/build
gmake

cd $CERN_ROOT/lib

# build shared libraries

for i in *.a; do
  mkdir xxx; cd xxx;
  cp ../$i .; ar -x $i;
  NN=$(echo $i | sed -e's/[.]a/.so/g');
  echo creating $NN;
  ld -shared *.o -soname $NN.1 -o $NN.1.0;
  mv $NN.1.0 ../;
  cd ..;
  /sbin/ldconfig -l $NN.1.0
  if test -e $NN.1; then ln -sf $NN.1 $NN; fi
  rm -rf xxx; 
done

